package com.odobenus.tools;

import java.net.URI;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpTools {
	public static String get(String url,List <NameValuePair> nvps) throws Exception {
	    // 创建Httpclient对象
	    CloseableHttpClient httpclient = HttpClients.createDefault();
	    // 创建URI对象，并且设置请求参数
	    URI uri = new URIBuilder(url).setParameters(nvps).build();
	    
	    // 创建http GET请求
	    HttpGet httpGet = new HttpGet(uri);
	    CloseableHttpResponse response = null;
	    try {
	        // 执行请求
	        response = httpclient.execute(httpGet);
	        // 判断返回状态是否为200
	        if (response.getStatusLine().getStatusCode() == 200) {
	            // 解析响应数据
	            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
	            return content;
	        }
	    } finally {
	        if (response != null) {
	            response.close();
	        }
	        httpclient.close();
	    }
		return null;
	}
}
